package com.pshcp.patient.task.job;

import com.external.pay.PayService;
import com.external.pay.domain.RefundDTO;
import com.external.pay.domain.RefundResDTO;
import com.pshcp.common.enums.PayBusinessEnum;
import com.pshcp.common.enums.RegPayStatusEnum;
import com.pshcp.domain.model.PatientOnlineOrder;
import com.pshcp.service.OnlineSessionService;
import com.pshcp.service.PatientOnlineMedicalRecordsService;
import com.pshcp.service.PatientOnlineOrderService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 退款任务，调用三方退费查询，状态补偿
 */
@Slf4j
@Component
public class OnlineOrderRefundStatusQueryJob extends QuartzJobBean {

    @Autowired
    private PatientOnlineOrderService onlineOrderService;

    @Autowired
    private PatientOnlineMedicalRecordsService medicalRecordsService;

    @Autowired
    private OnlineSessionService onlineSessionService;

    @Autowired
    private PayService payService;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("start OnlineOrderRefundStatusQueryJob");
        List<PatientOnlineOrder> onlineOrders = onlineOrderService.refundingList();
        if(CollectionUtils.isEmpty(onlineOrders)){
            log.info("OnlineOrderRefundStatusQueryJob is null. ignore task.");
            return;
        }
        onlineOrders.forEach(o -> {
            RefundDTO refundDTO = new RefundDTO();
            refundDTO.setOrderId(o.getId());
            refundDTO.setRefundOrderId(o.getId());
            refundDTO.setPayBusiness(PayBusinessEnum.ONLINE_PAY.getCode());
            try {
                RefundResDTO resDTO = payService.refundQuery(refundDTO);
                if(resDTO.getPayStatus() != null && resDTO.getPayStatus().intValue() == 0){
                    o.setPayStatus(RegPayStatusEnum.REFUND_OK.getCode());
                }
                if(resDTO.getPayStatus() != null && resDTO.getPayStatus().intValue() == 1){
                    o.setPayStatus(RegPayStatusEnum.REFUND_FAIL.getCode());
                }
                if(resDTO.getPayStatus() != null && resDTO.getPayStatus().intValue() == 2){
                    o.setPayStatus(RegPayStatusEnum.REFUND_ING.getCode());
                }
                onlineOrderService.update(o);
            } catch (Exception e) {
                log.error("OnlineOrderRefundStatusQueryJob fail", e);
            }
        });
    }

}
